<template>
  <div id="SceneView">
    <div id="mapView"></div>
    <div class="box1">
      <button @click="start">开始</button>
      <button @click="pause">暂停</button>
      <button @click="goOn">继续</button>
      <button @click="back">返回</button>
    </div>
  </div>
</template>

<script>
import { loadModules } from "esri-loader";
// import coordtransform from 'coordtransform'
import InitArcGisJs from "../utils/loadGisModules";
export default {
  name: "trackMobile",
  data() {
    return {
      ARCGIS: {}, //arcgis模块
      view: {},
      carPaths: [
        [121.43160205987387, 31.26282509543873],
        [121.43311812853624, 31.243252185609347],
        [121.43332323846386, 31.21490144418662],
        [121.43347989136313, 31.193205088384023],
        [121.43809041733759, 31.181609399594212],
        [121.45418772048085, 31.17353696840031],
        [121.46831357307458, 31.172864675859927],
        [121.49377424793417, 31.16690545305374],
        [121.528860025732, 31.16559997580725],
        [121.55417860513636, 31.170240012590355],
        [121.58254628484454, 31.177590947249314],
        [121.60882484452124, 31.217783107452398],
        [121.64174435867926, 31.238101062288138],
        [121.67130505486631, 31.24109202840721],
        [121.67696708443468, 31.182327796131737],
        [121.65674024528252, 31.15447638354427],
        [121.63311740175342, 31.128406807344984],
        [121.59983065975045, 31.12531572128321],
        [121.58627760788673, 31.142275568952122],
        [121.5818222405364, 31.15903999305297],
        [121.56576770695685, 31.18434576486628],
        [121.54860540628536, 31.19667755152712],
        [121.50845182240249, 31.218480922797255],
        [121.47883854788424, 31.255976160827387],
        [121.4750808650285, 31.301249060921286],
        [121.49736827722204, 31.349596859856305],
        [121.5156800475573, 31.365309806532697],
        [121.58217384953288, 31.373327010389673],
        [121.61804905125007, 31.36271016556091],
        [121.6145140998525, 31.320927100129904],
        [121.5681396884267, 31.30697346116576],
        [121.53307269834605, 31.297506804406854],
        [121.49031162272651, 31.285969983852624],
        [121.5665402937627, 31.262756450223478],
        [121.67194190551005, 31.26517877564264],
        [121.8504790852101, 31.348907479104916],
        [121.82894337600682, 31.545360203234335]
      ],
      // 移动图层
      moveLayer: null,
      moveCarGra: null,
      moving: null,
      startingPoint: {},
      startNum: 0,
      endNum: 0
    };
  },
  async created() {
    this.ARCGIS = await InitArcGisJs.init();
    let { Map, TileLayer, SceneView, FeatureLayer } = this.ARCGIS;
    const map = new Map({
      // basemap: "streets-night-vector",
      // showLabels: true,
      // maxZoom: 15,
      // zoom: 7,
      // minZoom: 6,
      // logo: false,
      // height: "100%",
      // fadeOnZoom: true
    });
    this.map = map;
    const CAMERA_Z = 27000,
      CAMERA_CENTER = [121.45897884146042, 31.246522700030482],
      // VIEW_ZOOM = 6.363478077483849;
      VIEW_ZOOM = 13;
    // VIEW_ZOOM_SPACE = 0.3;
    // 创建地图实例map
    this.view = new SceneView({
      container: "mapView",
      map: this.map,
      qualityProfile: "high"
      // camera: {
      //   position: {
      //     x: CAMERA_CENTER[0],
      //     y: CAMERA_CENTER[1],
      //     z: CAMERA_Z
      //     // spatialReference: { wkid: 102100 }
      //   },
      //   tilt: 0
      // },
      // zoom: VIEW_ZOOM,
      // center: CAMERA_CENTER,
      // qualityProfile: "medium", //  high, medium, low
      // viewingMode: "local",
      // screenSizePerspectiveEnabled: true,
      // highlightOptions: {
      //   haloOpacity: 0
      // }
    });
    var tiledUrl =
      "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer";
    var tiledLayer = new TileLayer({ url: tiledUrl });
    this.map.add(tiledLayer);
    let list = [];
    this.view.on("click", event => {
      var screenPoint = {
        //当前点击的经纬度
        x: event.x,
        y: event.y
      };
      let { longitude: x, latitude: y } = event.mapPoint;
      list.push([x, y]);
      console.log(JSON.stringify(list));
      this.view.hitTest(screenPoint).then(function(response) {
        let { latitude, longitude } = response.ground.mapPoint;
        console.log([longitude, latitude]);
        if (response.results.length > 0 && response.results[0].graphic) {
          console.log("这是当前点击的点位信息", response.results);
        }
      });
    });
    this.view.when(
      () => {
        // 地图加载完成
        setTimeout(() => {
          this.view.goTo({
            // 视角切换动画
            center: [this.carPaths[0][0], this.carPaths[0][1]], //终点坐标
            heading: 360, // 面向正南
            z: 10000,
            tilt: 0, //视图角度cos
            zoom: 13 //放大等级
          });
        }, 1000);
      },
      function(error) {
        console.error(error);
        alert("加载失败,稍后重新加载");
        window.reload();
      }
    );
    // 创建小车路线
    this.createCarPolyline();
  },
  mounted() {},
  methods: {
    createCarPolyline() {
      let { GraphicsLayer, Graphic } = this.ARCGIS;
      let polyline = {
        type: "polyline", // autocasts as new Polyline()
        paths: this.carPaths
      };
      let lineSymbol = {
        type: "simple-line", // autocasts as SimpleLineSymbol()
        color: [255, 0, 0],
        width: 2
      };
      var polylineGraphic = new Graphic({
        geometry: polyline,
        symbol: lineSymbol
      });
      this.view.graphics.add(polylineGraphic);
      // 开始创建小车
      // 初始化车辆
      let modelCar = this.initModelCar();
      this.moveLayer = new GraphicsLayer({
        id: "moveLayer"
      });
      this.map.add(this.moveLayer);
      this.moveCarGra = new Graphic({
        geometry: this.startingPoint,
        symbol: modelCar
      });
      this.moveLayer.add(this.moveCarGra);
    },
    // 根据坐标计算角度
    calcAngle(x1, y1, x2, y2) {
      let tan =
        (Math.atan(Math.abs((y2 - y1) / (x2 - x1))) * 180) / Math.PI + 90;
      if (x2 > x1 && y2 > y1) {
        return -tan + 180;
      } else if (x2 > x1 && y2 < y1) {
        return tan;
      } else if (x2 < x1 && y2 > y1) {
        return tan - 180;
      } else {
        return -tan;
      }
    },
    move(start, end) {
      let x1 = this.carPaths[start][0];
      let y1 = this.carPaths[start][1];
      let x2 = this.carPaths[end][0];
      let y2 = this.carPaths[end][1];

      //斜率
      let p = (y2 - y1) / (x2 - x1);
      //速度
      // let v = 0.002; // 过小会导致线路偏移
      let v = 0.009; // 过小会导致线路偏移
      this.moving = setInterval(() => {
        this.moveLayer.removeAll();
        this.startNum = start;
        this.endNum = end;
        //分别计算 x,y轴的方向和速度
        if (Math.abs(p) == Number.POSITIVE_INFINITY) {
          //垂直的时候斜率无穷大
          this.moveCarGra.geometry.y += v;
        } else {
          if (x2 < x1) {
            this.moveCarGra.geometry.x -= (1 / Math.sqrt(1 + p * p)) * v;
            this.moveCarGra.geometry.y -= (p / Math.sqrt(1 + p * p)) * v;
            // 创建行驶车辆
            let modelNewCar = this.setModelCar(x1, y1, x2, y2);
            this.moveLayer.add(
              new this.ARCGIS.Graphic({
                geometry: this.moveCarGra.geometry,
                symbol: modelNewCar
              })
            );
          } else {
            this.moveCarGra.geometry.x += (1 / Math.sqrt(1 + p * p)) * v;
            this.moveCarGra.geometry.y += (p / Math.sqrt(1 + p * p)) * v;
            // 创建行驶车辆
            let modelNewCar = this.setModelCar(x1, y1, x2, y2);
            this.moveLayer.add(
              new this.ARCGIS.Graphic({
                geometry: this.moveCarGra.geometry,
                symbol: modelNewCar
              })
            );
          }
        }
        if (
          Math.abs(this.moveCarGra.geometry.x - x2) <= v &&
          Math.abs(this.moveCarGra.geometry.y - y2) <= v
        ) {
          clearInterval(this.moving);
          this.startNum = start++;
          this.endNum = end++;
          if (end < this.carPaths.length) {
            this.move(start, end);
          }
        }
      }, 50);
    },
    // 开始
    start() {
      if (this.moving != undefined) {
        clearInterval(this.moving); //清除移动
      }
      this.moveCarGra.geometry = this.startingPoint;
      this.move(0, 1);
    },
    // 暂停
    pause() {
      clearInterval(this.moving);
    },
    // 继续
    goOn() {
      if (this.moving != undefined) {
        clearInterval(this.moving); //清除移动
      }
      this.move(this.startNum, this.endNum);
    },
    // 返回
    back() {
      let { Graphic } = this.ARCGIS;
      if (this.moving != null) {
        clearInterval(this.moving); //清除移动
      }
      this.moveLayer.removeAll();
      // 初始化车辆
      let modelNewCar = this.initModelCar();
      this.moveLayer.add(
        new Graphic({
          geometry: this.startingPoint,
          symbol: modelNewCar
        })
      );
    },
    // 初始化车辆
    initModelCar() {
      let x1 = this.carPaths[0][0];
      let y1 = this.carPaths[0][1];
      let x2 = this.carPaths[1][0];
      let y2 = this.carPaths[1][1];
      // 设置起点
      this.startingPoint = {
        type: "point",
        longitude: this.carPaths[0][0],
        latitude: this.carPaths[0][1]
      };
      let modelNewCar = {
        type: "picture-marker", // autocasts as new PictureMarkerSymbol()
        url: require("../assets/images/car.png"),
        // "https://static.arcgis.com/images/Symbols/Shapes/BlackStarLargeB.png",
        width: "40px",
        height: "40px"
        // symbolLayers: [
        //   {
        //     type: "object",
        //     // width: 300, //模型宽度ssss
        //     height: 468, //模型高度
        //     resource: {
        //       href: "https://avatar.csdnimg.cn/A/B/3/0_qq_40629447.jpg"
        //     },
        //     url: require("@/assets/logo.png"),
        //     heading: this.calcAngle(x1, y1, x2, y2) + 180 //朝向
        //   }
        // ]
      };
      return modelNewCar;
    },
    // 创建车辆
    setModelCar(x1, y1, x2, y2) {
      let modelNewCar = {
        type: "picture-marker",
        type: "picture-marker", // autocasts as new PictureMarkerSymbol()
        // url:
        //   "https://static.arcgis.com/images/Symbols/Shapes/BlackStarLargeB.png",
        url: require("../assets/images/car.png"),
        // "https://static.arcgis.com/images/Symbols/Shapes/BlackStarLargeB.png",
        width: "40px",
        height: "40px"
        // symbolLayers: [
        //   {
        //     type: 'object',
        //     // width: 300, //模型宽度ssss
        //     height: 468, //模型高度
        //     resource: {
        //       href: 'gltf/red_car.gltf',
        //     },
        //     url:require("@/assets/logo.png"),
        //     heading: this.calcAngle(x1, y1, x2, y2) + 180, //朝向
        //   },
        // ],
      };
      return modelNewCar;
    }
  }
};
</script>

<style>
@import "https://js.arcgis.com/4.20/esri/css/main.css";

html,
body,
#mapView {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}
.dot_box {
  z-index: 2;
  position: fixed;
  width: 20px;
  height: 20px;
  background: #0080ff;
  border-radius: 50%;
}
.line_ele {
  z-index: 2;
  position: absolute;
  top: 50%;
  left: 0;
  margin-top: -1px;
  height: 1px;
  border-bottom: 1px solid #0080ff;
}
.box {
  z-index: 2;
  display: none;
  position: fixed;
  width: 300px;
  height: 300px;
  border: 2px solid #ddd;
}
.box1 {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 9;
}
#SceneView {
  position: absolute;
  width: 100%;
  height: 100%;
}
.esri-component.esri-attribution.esri-widget {
  display: none;
}
</style>
